package com.jianyun.jyzs.fragment;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.jianyun.jyzs.R;
import com.jianyun.jyzs.activity.FlowExamineActivity;
import com.jianyun.jyzs.activity.FlowExamineDetailActivity;
import com.jianyun.jyzs.activity.ShowFileActivity;
import com.jianyun.jyzs.base.MVPBaseFragment;
import com.jianyun.jyzs.constant.SysConstant;
import com.jianyun.jyzs.presenter.WaitDoPresenter;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.NetUtil;
import com.jianyun.jyzs.view.iview.IWaitDoView;

import butterknife.BindView;

import static com.jianyun.jyzs.activity.FlowExamineHtmlActivity.shenpiRefresh;

/**
 * 流程审批 我的待办
 * Created by yangshijun on 2018/5/29.
 */

public class WaitDoFragment extends MVPBaseFragment<IWaitDoView, WaitDoPresenter> implements IWaitDoView {
    @BindView(R.id.nullNetWork)
    LinearLayout nullNetWork;
    @BindView(R.id.webview)
    WebView webview;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;

    public WebSettings webSettings;
    public String[] data;//用来保存搜索的条件
    private FlowExamineActivity ac;
    public String jumpUrl;
    private String userId;
    public String reFreshUrl="";


    private boolean askedgalleryPermission = false;
    private int galleryPermissionReqCode = 202;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ac = (FlowExamineActivity) activity;
    }

    @Override
    protected void initView() {

    }

    public void setJumpUrl(String JumpUrl){
        this.jumpUrl=JumpUrl;
    }

    @Override
    protected void initData() {
        data = new String[4];
        userId = LoginCache.getInstance().getUserInfo().getUserId();
        webSettings = webview.getSettings();
        //设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        //设置支持缩放
        webSettings.setBuiltInZoomControls(false);
        //放开storage缓存机制
        webSettings.setDomStorageEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webview.addJavascriptInterface(new JavaScriptObject(), "control");//传递对象进行交互
        webview.setDownloadListener(new MyWebViewDownLoadListener());
        searchData();
    }

    /**
     * 点击查询条件搜索后执行此方法
     */
    public void searchData() {
//        String sp = PreferrenceUtil.getPreferencesData(ac, SysConstant.LOGIN_ERPROOTURL);
        String erpRootUrl = LoginCache.getInstance().getLoginCache().getErpRootUrl();
        Log.i("test","根目录WaitDoFragment:"+erpRootUrl);
        String weburl =erpRootUrl+ SysConstant.http_url_myWorkFlowUrl.replaceAll("\\{employeeid\\}", userId);
        if (data != null) {
            weburl += "&insName=" + (data[0] == null ? "" : data[0]);
            weburl += "&taskName=" + (data[1] == null ? "" : data[1]);
            weburl += "&sendEmployeeid=" + (data[2] == null ? "" : ac.createUserId);
            weburl += "&sendTime=" + (data[3] == null ? "" : data[3]);
        }
        if (this.jumpUrl!=null||! TextUtils.isEmpty(jumpUrl)){
            weburl=erpRootUrl+jumpUrl;
        }
        //if (NetUtil.checkNetType(getActivity())) {
            //加载需要显示的网页
        reFreshUrl=weburl;
            webview.loadUrl(weburl);
            Log.i("test","url:"+weburl);
            //设置Web视图
            webview.setWebViewClient(new webViewClient());

//        } else {
//            webview.setVisibility(View.GONE);
//            nullNetWork.setVisibility(View.VISIBLE);
//        }
    }

    public void reFreshView(){
        if (webview!=null){
            webview.loadUrl(reFreshUrl);

        }
    }


    public class JavaScriptObject {


        @JavascriptInterface
        public void refreshHtml() {
            Log.i("test", "审批刷新");
        }

    }
    /**
     * webview点击下载
     */

    @Override
    protected int initContentLayout() {
        return R.layout.activity_app_workflow_item;
    }

    @Override
    public WaitDoPresenter createPresenter() {
        return new WaitDoPresenter();
    }

    class MyWebViewDownLoadListener implements DownloadListener {

        @Override
        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
            showFile(url);
        }

    }

    public void showFile(String url) {
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            //有权限
            //其他手机 下载 打开
            startActivity((new Intent(getContext(), ShowFileActivity.class))
                    .putExtra("type", -1)
                    .putExtra("id", -1)
                    .putExtra("folderID", "workFlow")
                    .putExtra("remotepath", url));
        } else if (!askedgalleryPermission) {
            ActivityCompat.requestPermissions(getActivity(),
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    galleryPermissionReqCode);
            askedgalleryPermission = true;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    //Web视图
    private class webViewClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {//网页页面开始加载的时候
            super.onPageStarted(view, url, favicon);
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
//	         //页面下载完毕,却不代表页面渲染完毕显示出来
//            if (webview.getContentHeight() != 0) { //这个时候网页才显示
            progressBar.setVisibility(View.INVISIBLE);
//            }
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.i("test","加载"+url);
            // handle different requests for different type of files
            // this example handles downloads requests for .apk and .mp3 files
            // everything else the webview can handle normally
//            if (url.endsWith("isDowload=yes")) {
            //跳转界面
            Intent intent = new Intent(getActivity(), FlowExamineDetailActivity.class);
            intent.putExtra("url",url);
            //startActivity(intent);
            startActivityForResult(intent, shenpiRefresh);
//            } else {
                //view.loadUrl(url);
//            }
            return true;
        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            //这里进行无网络或错误处理，具体可以根据errorCode的值进行判断，做跟详细的处理。
            view.loadUrl("file:///android_asset/error.html");
        }
    }
}
